package io.shdxhl.simplerpc.client.discovery.zk;

import io.shdxhl.simplerpc.client.discovery.SimpleServiceDiscovery;
import io.shdxhl.simplerpc.client.provider.ServiceProvider;
import io.shdxhl.simplerpc.code.cache.SimpleProviderCache;
import io.shdxhl.simplerpc.code.zk.ZkUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class ZkServiceDiscovery implements SimpleServiceDiscovery {
    @Autowired
    private ZkUtil zkUtil;

    @Autowired
    private SimpleProviderCache simpleProviderCache;

    @Override
    public void discover() {
        List<String> serverList = zkUtil.getServerList();
        if(Objects.nonNull(serverList) && serverList.size() > 0) {
            for (String server : serverList) {
                //获取指定接口下的节点列表
                List<ServiceProvider> providers= zkUtil.getServerInfos(server);
                //将接口以及对应提供的列表存储到缓存中
                simpleProviderCache.put(server, providers);
                //订阅接口的变更
                log.info("订阅了接口:{}， 提供者列表名为：{}", server,providers);
                zkUtil.subscribe(server);
            }
        }

    }
}
